package com.isasc.demo.pooled.datasource;

import lombok.Getter;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

/**
 * @author: ywy
 * @date: 2022-10-17
 * @desc:
 */
@Component
@Getter
public class MyDataSource implements DataSource {
    private ConnectionFactory factory;

    private GenericObjectPool<MyConnection> pool;

    public MyDataSource() {
        factory = new ConnectionFactory();
        pool = new GenericObjectPool<>(factory);
        factory.setPool(pool);
    }

    @Override
    public Connection getConnection() throws SQLException {
        try {
            return pool.borrowObject();
        } catch (Exception e) {
            throw new SQLException(e);
        }
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return getConnection();
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
